package club.haomoon.boss.helper;

import club.haomoon.core.entity.system.RechargeOrderData;
import club.haomoon.core.mapper.system.RechargeOrderMapper;
import club.haomoon.core.plugin.wechat.WxPayDriver;
import club.haomoon.core.plugin.wechat.request.RefundRequestV3;
import club.haomoon.core.util.AmountUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import org.springframework.stereotype.Component;
import java.math.BigInteger;

/**
 * -------------------------
 * @Description: 微信支付助手类
 * @Author: Wangjianwei
 * @Date: 2025/02/19 11:04
 * -------------------------
 */
@Component
public class WxpayHelper {


    /**
     * w微信退款
     * @param rechargeOrder
     * @param refundSn
     * @throws WxPayException
     */
    public String wxPayRefund(RechargeOrderData rechargeOrder, String refundSn,RechargeOrderMapper rechargeOrderMapper) throws WxPayException {
        String refundTransactionId = null;
        RefundRequestV3 requestV3 = new RefundRequestV3();
        requestV3.setTransactionId(rechargeOrder.getTransactionId());
        requestV3.setOutTradeNo(rechargeOrder.getSn());
        requestV3.setOutRefundNo(refundSn);
        requestV3.setTotalAmount(AmountUtil.yuan2Fen(rechargeOrder.getOrderAmount().toString()));
        requestV3.setRefundAmount(AmountUtil.yuan2Fen(rechargeOrder.getOrderAmount().toString()));
        WxPayRefundV3Result result = WxPayDriver.refund(requestV3);

        refundTransactionId = result.getTransactionId();
        rechargeOrder.setRefundTransactionId(new BigInteger(refundTransactionId));
        rechargeOrderMapper.updateById(rechargeOrder);

        return JSONObject.toJSONString(result);
    }
}
